<?php
/**
 * Project: HTPHouDuan
 * User: xilibo
 * Date: 2018/1/24
 */

namespace app\common\model;

use think\Model;
use think\Db;
use think\Request;

/**
 * 用户模型
 */
class UserModel extends BaseModel
{
    protected $tableName = 'user';

    public function saveUser($userInfo, $where = [])
    {
        $time = time();
        $userData['user_type'] = '2';
        $userData['user_login'] = $userInfo['user_login'];
        $userData['user_nickname'] = $userInfo['user_login'];
        $userData['user_pass'] = isset($userInfo['user_pass']) ? cmf_password($userInfo['user_pass']) : cmf_password($userInfo['user_login'] . $time);
        $userData['last_login_time'] = $time;
        $userData['last_login_ip'] = Request::instance()->ip();
        $userData['create_time'] = $time;

        return parent::saveData($userData, $where);
    }

    /**
     * 验证用户
     */
    public function validateUser($userInfo)
    {
        $where = [
            'user_login' => $userInfo['user_login'],
            'user_pass' => cmf_password($userInfo['user_pass']),
        ];

        return parent::existsRow($where);
    }

    /**
     * 额度转换
     * @param  string $order_bn 订单号
     * @param  string $type     in: 转入 out: 转出
     * @return array           前后余额
     */
    public function recharge($userId, $orderBn, $type, $money)
    {
        $money = floatval($money);
        $lastBalance = $this->balance(['id' => $userId])['money'];
        $curBalance = 0;

        if ($type == 'in'){
            $curBalance = $lastBalance + $money;
        } else if ($type == 'out'){
            $curBalance = $lastBalance - $money;
            if ($curBalance <= 0 || $lastBalance <= 0){
                return -1;
            }
        } else {
            return false;
        }

        $data = [
            'balance' => $curBalance,
        ];

        $where = [
            'id' => $userId,
            ];
        $result = parent::save($data, $where);
        $change = $curBalance - $lastBalance;

        if ($result){
			$balanceLogModel = model('user_balance_log');
			if ($balanceLogModel->existsRow(['order_bn' => $orderBn])){
				return -2;
			}

            $resultLog = $balanceLogModel->writeRechargeLog($where['id'], $orderBn, $curBalance, $change);
            if (! $resultLog) {
                return false;
            }

            return [
                'oMoney' => $lastBalance,
                'cMoney' => $curBalance,
                ];
        }

        return false;
    }

    /**
     * 查询用户余额
     * @param  array $where [description]
     * @return float        余额
     */
    public function balance($where)
    {
        $row = $this->getRow($where, 'balance');

        return ['money' => $row['balance']];
    }

    public function getInfo($where,$field='*',$insert=false){
        $re = Db::name($this->table)->field($field)->where($where)->cache(!$insert)->find();

        if (empty($re)) {
            if ($insert && isset($where['user_login'])) {
                db('user')->insert([
                    'user_login' => $where['user_login'],
                    'user_nickname' => $where['user_login'],
                    'create_time' => time(),
                    'avatar' => 1
                ]);
                $re = Db::name($this->table)->field($field)->where($where)->cache(!$insert)->find();
            }

        } else {

            if (!empty($re['avatar'])){
                $re['avatar'] = 1;
            }
            if (!empty($re['history_list'])){
                $re['history_list'] = json_decode($re['history_list'],true);
                if(is_array($re['history_list'])){
                    $re['history_list'] = Db::name('game')->field('game_logo,game_name,play_url')->where('id','in',$re['history_list'])->cache(!$insert)->select();
                }
            }
        }
        session('user',$re);
        return $re;
    }
    
    public function setInfo($where,$data){
        $re = db('user')->where($where)->cache(true)->update($data);
        $userInfo=db('user')->where($where)->cache(true)->find();
        session('user',$userInfo);
        if ($re === false) {
            return ['code' => 0, 'msg' => '数据库写入出错'];
        } else {
            return ['code' => 1, 'msg' => '修改成功'];;
        }
    }
}
